package com.zhaopin.leetcode;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Administrator
 * @create 2020-07-17 15:00
 *
 * 给定 nums = [2, 7, 11, 15], target = 9
 *
 * 因为 nums[0] + nums[1] = 2 + 7 = 9
 * 所以返回 [0, 1]
 *
 * 来源：力扣（LeetCode）
 * 链接：https://leetcode-cn.com/problems/two-sum
 * 著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。
 *
 */
public class One {

    public static void main(String[] args) {
        int[] nums = {11,2,15,7};
        int target = 9;
        int[] retAttr = twoSum2(nums,target);
        for (int i : retAttr) {
            System.out.print(i + " ");
        }
    }

    public static int[] twoSum(int[] nums, int target) {

        int left = 0;
        int right = 0;
        for (int i = 0; i < nums.length; i++) {
            int theRest = target-nums[i];
            for (int i1 = i+1; i1 < nums.length; i1++) {
                if(theRest == nums[i1]){
                    left = i;
                    right = i1;
                }
            }
        }
        int[] retAttr = {left,right};
        return retAttr;
    }

    public static int[] twoSum2(int[] nums, int target) {

        int[] retAttr = new int[2];
        Map<Integer, Integer> map = new HashMap<>();

        for (int i = 0; i < nums.length; i++) {
            if(map.containsKey(nums[i])){
                retAttr[0] = map.get(nums[i]);
                retAttr[1] = i;
                return retAttr;
            }
            int s = target - nums[i];
            map.put(s,i);
        }
        return null;
    }

}
